
package com.jf.cloud.order.listener;

import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.multishop.bo.OrderChangeShopWalletAmountBO;
import com.jf.cloud.api.order.constant.PurchaseOrderWaitStatus;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.bo.PayRefundBO;
import com.jf.cloud.common.order.vo.OrderItemVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.order.constant.RefundType;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.service.OrderItemService;
import com.jf.cloud.order.service.OrderService;
import com.jf.cloud.order.vo.OrderRefundVO;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 *
 * @author zz
 * @date 2021/1/7
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_REFUND_TOPIC,consumerGroup = RocketMqConstant.ORDER_REFUND_TOPIC)
public class OrderRefundConsumer implements RocketMQListener<OrderRefundVO> {

    @Autowired
    private RocketMQTemplate orderRefundPaymentTemplate;
    @Autowired
    private RocketMQTemplate orderRefundShopTemplate;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private SegmentFeignClient segmentFeignClient;

    private static final Logger LOG = LoggerFactory.getLogger(OrderRefundConsumer.class);

    @Override
    public void onMessage(OrderRefundVO orderRefundVo) {

        PayRefundBO payRefundBO = new PayRefundBO();
        payRefundBO.setRefundId(orderRefundVo.getRefundId());
        payRefundBO.setRefundAmount(orderRefundVo.getRefundAmount());
        payRefundBO.setOrderId(orderRefundVo.getOrderId());
        payRefundBO.setPayId(orderRefundVo.getPayId());
        payRefundBO.setPayIds(orderRefundVo.getPayIds());
        SendStatus sendPaymentStatus = null;
        // 未成团退款的订单已经处理过了，不需要再处理
        if (!Objects.equals(orderRefundVo.getUnSuccessGroupOrder(), 1)) {
            // 发送退款服务进行退款的通知
            sendPaymentStatus = orderRefundPaymentTemplate.syncSend(RocketMqConstant.ORDER_REFUND_PAYMENT_TOPIC, new GenericMessage<>(payRefundBO)).getSendStatus();
        }
        // 如果是待采购的订单，商家平台供应商不用退钱
        if(Objects.equals(orderRefundVo.getWaitPurchase(),1)){
            return;
        }
        // 锁定商家钱包结算金额
        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = getOrderChangeShopWalletAmountBO(orderRefundVo);

        // 生成钱包id
        int num = 1;
        if (!Objects.equals(orderChangeShopWalletAmountBO.getSupplierHandleStatus(),-1)) {
            LOG.info("非商家自行处理{}", orderChangeShopWalletAmountBO.getSupplierHandleStatus());
            num++;
        }
        // 店铺记录id
        if(Objects.equals(orderChangeShopWalletAmountBO.getWaitPurchase(), PurchaseOrderWaitStatus.PURCHASED.value())){
            LOG.info("采购完成{}", orderChangeShopWalletAmountBO.getWaitPurchase());
            num++;
        }
        if(Objects.nonNull(orderChangeShopWalletAmountBO.getSupplierId()) && !Objects.equals(orderChangeShopWalletAmountBO.getSupplierId(), 0)){
            LOG.info("供应商id不为空{}", orderChangeShopWalletAmountBO.getSupplierId());
            num++;
        }
        ServerResponseEntity<List<Long>> segmentEntity = segmentFeignClient.batchGetSegmentId(DistributedIdKey.MALL4CLOUD_SHOP_WALLET_LOG, num);
        if (!segmentEntity.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        orderChangeShopWalletAmountBO.setWalletLogIds(segmentEntity.getData());
        // 减少商家待结算金额
        SendStatus sendShopStatus = orderRefundShopTemplate.syncSend(RocketMqConstant.ORDER_REFUND_SHOP_TOPIC, new GenericMessage<>(orderChangeShopWalletAmountBO)).getSendStatus();

        if (Objects.nonNull(sendPaymentStatus) && !Objects.equals(sendPaymentStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }

        if (!Objects.equals(sendShopStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
    }


    /**
     * 获取订单待结算金额
     */
    private OrderChangeShopWalletAmountBO getOrderChangeShopWalletAmountBO(OrderRefundVO orderRefundVO) {

        // 同意退款，判断商家是否还有金额进行退款
        Order order = orderService.getByOrderId(orderRefundVO.getOrderId());
        if (order == null) {
            throw new LuckException("未找到该订单信息");
        }

        // 实付金额
        Long actualTotal;
        Long platformCommission;
        Double rate = 0.0;
        Long distributionAmount;
        Long shopAllowanceAmount;
        if (Objects.equals(orderRefundVO.getRefundType(), RefundType.ALL.value())) {
            actualTotal = order.getActualTotal();
            platformCommission = order.getPlatformCommission();
            distributionAmount = order.getDistributionAmount();
            shopAllowanceAmount = order.getReduceAmount() - order.getPlatformAmount();
        } else {
            OrderItemVO item = orderItemService.getByOrderItemId(orderRefundVO.getOrderItemId());
            actualTotal =  item.getActualTotal();
            // 平台佣金
            platformCommission = item.getPlatformCommission();
            rate = item.getRate();
            shopAllowanceAmount = item.getShareReduce() - item.getPlatformShareReduce();
            distributionAmount = item.getDistributionAmount() + item.getDistributionParentAmount();
        }


        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = new OrderChangeShopWalletAmountBO();
        orderChangeShopWalletAmountBO.setOrderStatus(order.getStatus());
        orderChangeShopWalletAmountBO.setActualTotal(actualTotal);
        orderChangeShopWalletAmountBO.setRefundAmount(orderRefundVO.getRefundAmount());
        orderChangeShopWalletAmountBO.setPlatformAllowanceAmount(orderRefundVO.getPlatformRefundAmount());
        orderChangeShopWalletAmountBO.setShopAllowanceAmount(shopAllowanceAmount);
        orderChangeShopWalletAmountBO.setOrderId(order.getOrderId());
        orderChangeShopWalletAmountBO.setRefundId(orderRefundVO.getRefundId());
        orderChangeShopWalletAmountBO.setShopId(orderRefundVO.getShopId());
        orderChangeShopWalletAmountBO.setOrderItemId(orderRefundVO.getOrderItemId());
        orderChangeShopWalletAmountBO.setPlatformCommission(platformCommission);
        orderChangeShopWalletAmountBO.setChangePlatformCommission(orderRefundVO.getPlatformRefundCommission());
        orderChangeShopWalletAmountBO.setRate(rate);
        orderChangeShopWalletAmountBO.setDistributionAmount(distributionAmount);
        orderChangeShopWalletAmountBO.setFreightAmount(orderRefundVO.getFreightAmount());
        orderChangeShopWalletAmountBO.setWaitPurchase(order.getWaitPurchase());
        orderChangeShopWalletAmountBO.setPlatformFreeFreightAmount(order.getPlatformFreeFreightAmount());
        // 供应商相关
        orderChangeShopWalletAmountBO.setSupplierFreightAmount(orderRefundVO.getSupplierFreightAmount());
        orderChangeShopWalletAmountBO.setSupplierHandleStatus(orderRefundVO.getSupplierHandleStatus());
        orderChangeShopWalletAmountBO.setSupplierId(order.getSupplierId());
//        orderChangeShopWalletAmountBO.setPurchaseRefundAmount(purchaseRefundAmount);
        orderChangeShopWalletAmountBO.setChangePurchaseAmount(orderRefundVO.getPurchaseRefundAmount());
//        orderChangeShopWalletAmountBO.setPurchasePlatformCommission(purchasePlatformCommission);
        orderChangeShopWalletAmountBO.setChangePurchasePlatformCommission(orderRefundVO.getPurPlatformRefundCommission());
        orderChangeShopWalletAmountBO.setLastOrder(orderRefundVO.isLastOrder());
        return orderChangeShopWalletAmountBO;
    }
}
